/**
 * X Clock
 * Analog clock for minix.
 */

#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include "clock.h"
#include <img.h>
#include <stdlib.h>

int
main(int argc,char **argv)
{
	struct tm * t;
	colorT colour = {0,0,0};
	imgT * screen;
	time_t secTime;
	int flags,aux,res;
	imgT *bkg;
	rectT frst;


	if (argc<2 || (bkg=imgLoad(argv[1],IMG_BMP))==NULL || (res=getResolutionCode(bkg))==-1  )
	{
	      res=2;
	      bkg=NULL;
	}


	if( (screen=imgScreen(res))== NULL )
		return 1;


	frst.w = screen->w;
	frst.h = screen->h;
	frst.orig.x = 0;
	frst.orig.y = 0;


	imgBlt(bkg, frst, screen, frst, BLT_CPY);

    	flags = fcntl(0, F_GETFL, 0);


	/*Pongo non block*/
	fcntl(0, F_SETFL, flags | O_NONBLOCK);

	/*Inicializo el reloj.*/
	initClock(screen);

	while(read(0,&aux,1)==-1)
	{

		/*Limpiar pantalla.*/
			imgClear(screen, colour);
			imgBlt(bkg, frst, screen, frst, BLT_CPY);

		/*Dibujar Reloj en pantalla.*/
		drawClock();

		/*Obtener la hora*/
		secTime = time(NULL);
		t = localtime(&secTime);

		/*Dibujar agujas.*/
		drawHours(*t);
		drawMinutes(*t);
		drawSeconds(*t);

		imgScreenRefresh(screen);

		/* Este sleep en realidad no hace falta porque el programa ya es de por si lento.
		 *
		 * sleep(1); */
	}

	/*Pongo block*/
	fcntl(0, F_SETFL, flags);

	imgFree(screen);
	endClock();

	printf("...but you are older, shorter of breath, and one day closer to death.\n");

	return 0;
}
